package com.jeecg.p3.divination.web;

import com.alibaba.fastjson.JSONObject;
import com.jeecg.p3.baseApi.service.BaseApiJwidService;
import com.jeecg.p3.baseApi.service.BaseApiSystemService;
import com.jeecg.p3.baseApi.util.EmojiFilter;
import com.jeecg.p3.divination.entity.WxActDivination;
import com.jeecg.p3.divination.entity.WxActDivinationRecord;
import com.jeecg.p3.divination.entity.WxActDivinationRegistration;
import com.jeecg.p3.divination.entity.WxActDivinationShare;
import com.jeecg.p3.divination.exception.DivinationException;
import com.jeecg.p3.divination.exception.DivinationExceptionEnum;
import com.jeecg.p3.divination.service.WxActDivinationRecordService;
import com.jeecg.p3.divination.service.WxActDivinationRegistrationService;
import com.jeecg.p3.divination.service.WxActDivinationService;
import com.jeecg.p3.divination.service.WxActDivinationShareService;
import org.apache.velocity.VelocityContext;
import org.jeecgframework.p3.base.vo.WeixinDto;
import org.jeecgframework.p3.core.common.utils.AjaxJson;
import org.jeecgframework.p3.core.common.utils.StringUtil;
import org.jeecgframework.p3.core.util.WeiXinHttpUtil;
import org.jeecgframework.p3.core.util.plugin.ViewVelocity;
import org.jeecgframework.p3.core.utils.common.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/divination")
public class DivinationController {
	public final static Logger LOG = LoggerFactory
			.getLogger(DivinationController.class);
	@Autowired
	private WxActDivinationService divinationService;
	@Autowired
	private WxActDivinationRecordService wxActDivinationRecordService;
	@Autowired
	private BaseApiJwidService baseApiJwidService;
	@Autowired
	private BaseApiSystemService baseApiSystemService;	
	@Autowired
	private WxActDivinationRegistrationService wxActDivinationRegistrationService;
	@Autowired
	private WxActDivinationShareService wxActDivinationShareService;
	/**
	 * 摇签首页
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/toYaoqian", method = { RequestMethod.GET,
			RequestMethod.POST })
	public void toYaoqian(@ModelAttribute WeixinDto weixinDto,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		LOG.info("toYaoqian parameter WeixinDto={}.",
				new Object[] { weixinDto });
		VelocityContext velocityContext = new VelocityContext();
		String viewName = "divination/default/vm/yaoqian.vm";
		// 所需要的参数
		// 装载微信所需参数
		String jwid = weixinDto.getJwid();
		String appid = weixinDto.getAppid();
		String actId = weixinDto.getActId();
		try {
			// 参数验证
			validateBargainDtoParam(weixinDto);
			// 获取活动信息
			WxActDivination divination = divinationService.queryById(actId);
			long date = new Date().getTime();
			if (divination == null) {
				throw new DivinationException(
						DivinationExceptionEnum.DATA_NOT_EXIST_ERROR, "活动不存在");
			}
			if(StringUtil.isEmpty(weixinDto.getOpenid())){
				throw new DivinationException(
						DivinationExceptionEnum.DATA_NOT_EXIST_ERROR,
						"参与人的openid不能为空!");
			}
			if ("0".equals(divination.getActiveFlag())) {
				throw new DivinationException(
						DivinationExceptionEnum.ACT_BARGAIN_NO_START, "活动未激活！");
			}
			if (date<divination.getStartTime().getTime()) {
				throw new DivinationException(
						DivinationExceptionEnum.ACT_BARGAIN_NO_START, "活动未开始！");
			}
			if (date>divination.getEndTime().getTime()) {
				throw new DivinationException(
						DivinationExceptionEnum.ACT_BARGAIN_END, "活动已结束！");
			}
			//--update-begin---author:huangqingquan---date:20161125-----for:是否关注可参加---------------
			try {
				if("0".equals(divination.getFoucsUserCanJoin())){//如果活动设置了需要关注用户才能参加	
					velocityContext.put("qrcodeUrl", baseApiJwidService.getQrcodeUrl(jwid));
					JSONObject userobj = WeiXinHttpUtil.getGzUserInfo(weixinDto.getOpenid(),weixinDto.getJwid());
					if(userobj!=null&&userobj.containsKey("subscribe")){
						if(!"1".equals(userobj.getString("subscribe"))){
							velocityContext.put("subscribeFlage", "1");
						}
					}else{
						velocityContext.put("subscribeFlage", "1");
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			//--update-end---author:huangqingquan---date:20161125-----for:是否关注可参加---------------
			Integer count = wxActDivinationRecordService.queryCountByOpenidAndActId(actId, weixinDto.getOpenid());
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
			Integer countPerDay = wxActDivinationRecordService.queryCountByOpenidAndActIdPerDay(actId, weixinDto.getOpenid(), sdf.format(date));
			Integer divinationCount = divination.getCount();
			Integer divinationNumPerDay = divination.getNumPerDay();
			Integer num=0;
			String flag="true";
			if(divinationCount==null){
				divinationCount=0;
			}
			if(divinationNumPerDay==null){
				divinationNumPerDay=0;
			}
			if(divinationNumPerDay!=0){
				if(divinationCount!=0){
					if(divinationCount<divinationNumPerDay){
						divinationNumPerDay=divinationCount;
					}
					
					if(divinationCount-count<divinationNumPerDay-countPerDay){
						num=divinationCount-count;
					}else{
						num=divinationNumPerDay-countPerDay;
					}
				}else{
					num=divinationNumPerDay-count;
				}
			}else{
				if(divinationCount!=0){
					num=divinationCount-count;
				}else{
					velocityContext.put("flag", flag);
				}
			}
			//update-begin--Author:zhangweijian  Date: 20180308 for：摇签活动的参与总人数和平均值查询
			String accounts=wxActDivinationRecordService.getAccountsByactId(actId);
			String actAve=wxActDivinationRecordService.getAveByactId(actId);
			//update-begin--Author:zhangweijian  Date: 20180308 for：摇签活动bug修改
			if(accounts==null&&accounts==""){accounts="0";}
			String average=null;
			if(actAve!=null&&actAve!=""){
				//保留两位小数
				average=actAve.substring(0,actAve.indexOf("."));
			}else{
				average="0";
			}
			//update-end--Author:zhangweijian  Date: 20180308 for：摇签活动bug修改
			//根据参与人的openid查询访问人的报名信息 
			WxActDivinationRegistration wxActDivinationRegistrations=wxActDivinationRegistrationService.queryRegistrationByOpenidAndActId(weixinDto.getOpenid(), weixinDto.getActId());
			//插入注册记录
			if(wxActDivinationRegistrations==null){
				Date refDate=new Date();
				WxActDivinationRegistration wxActDivinationRegistration=new WxActDivinationRegistration();
				wxActDivinationRegistration.setActId(weixinDto.getActId());
				wxActDivinationRegistration.setOpenid(weixinDto.getOpenid());
				wxActDivinationRegistration.setHead("");
				wxActDivinationRegistration.setNickName(weixinDto.getNickname());
				wxActDivinationRegistration.setUseCounts(0);
				wxActDivinationRegistration.setCreateTime(refDate);
				wxActDivinationRegistration.setJwid(divination.getJwid());
				wxActDivinationRegistrationService.doAdd(wxActDivinationRegistration);
			}
			WxActDivinationShare wxActDivinationShares=wxActDivinationShareService.queryOneByDate(actId, weixinDto.getOpenid(), sdf.format(new Date()));
			if(wxActDivinationShares!=null&&"0".equals(divination.getExtraLuckyDraw())){
				velocityContext.put("extraTimes", "1");
			}else{
				velocityContext.put("extraTimes", "0");
			}
			velocityContext.put("extraLuckyDraw", divination.getExtraLuckyDraw());
			velocityContext.put("accounts", accounts);	
			velocityContext.put("average", average);
			//update-end--Author:zhangweijian  Date: 20180308 for：摇签活动的参与总人数和平均值查询
			velocityContext.put("num", num);
			velocityContext.put("weixinDto", weixinDto);
			velocityContext.put("divination", divination);
			velocityContext.put("nonceStr", WeiXinHttpUtil.nonceStr);// 必填，生成签名的随机串
			velocityContext.put("timestamp", WeiXinHttpUtil.timestamp);// 必填，生成签名的时间戳
			velocityContext.put("hdUrl", divination.getHdurl());
			velocityContext.put("appId", appid);// 必填，公众号的唯一标识
			velocityContext.put("signature",WeiXinHttpUtil.getRedisSignature(request, jwid));// 必填，签名，见附录1
			//update-begin--Author:zhangweijian  Date: 20180309 for：底部logo通用方法
			velocityContext.put("huodong_bottom_copyright", baseApiSystemService.getHuodongLogoBottomCopyright(divination.getCreateBy()));
			//update-end--Author:zhangweijian  Date: 20180309 for：底部logo通用方法
		} catch (DivinationException e) {
			e.printStackTrace();
			LOG.error("divination toYaoqian error:{}", e.getMessage());
			//update-begin--Author:zhangweijian  Date: 20180320 for：活动开始结束页面
			viewName = "divination/default/vm/yaoqian.vm";
			if(e.getDefineCode().equals("02007")){
				velocityContext.put("act_Status", "noStart");
				velocityContext.put("act_Status_Msg", "活动未开始");
			}else if(e.getDefineCode().equals("02008")){
				velocityContext.put("act_Status", "end");
				velocityContext.put("act_Status_Msg", "活动已结束");
			}else{
				viewName= "system/vm/error.vm";
			}
			//update-end--Author:zhangweijian  Date: 20180320 for：活动开始结束页面
			velocityContext.put("errCode", e.getDefineCode());
			velocityContext.put("errMsg", e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			LOG.error("divination toYaoqian error:{}",e);
			velocityContext.put("errCode",DivinationExceptionEnum.SYS_ERROR.getErrCode());
			velocityContext.put("errMsg",DivinationExceptionEnum.SYS_ERROR.getErrChineseMsg());
			viewName= "system/vm/error.vm";
		}
		ViewVelocity.view(request, response, viewName, velocityContext);
	}
	/**
	 * 错误页面
	 * @param errorCode
	 * @return
	 */
	private String chooseErrorPage(String errorCode){
		if(errorCode.equals("02007")){
			return "system/vm/before.vm";
		}else if(errorCode.equals("02008")){
			return "system/vm/over.vm";
		}else{
			return"system/vm/error.vm";
		}
	}
	/*
	 * 活动规则
	 */
	@RequestMapping(value = "/detail", method = { RequestMethod.GET,
			RequestMethod.POST })
	public void detail(@ModelAttribute WeixinDto weixinDto,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		// 装载微信所需参数
		String actId = weixinDto.getActId();
		String viewName = "divination/default/vm/detail.vm";
		VelocityContext velocityContext = new VelocityContext();
		try {
			// 获取活动信息
			WxActDivination divination = divinationService.queryById(actId);
			if (divination == null) {
				throw new DivinationException(
						DivinationExceptionEnum.DATA_NOT_EXIST_ERROR, "活动不存在");
			}
			velocityContext.put("divination", divination);
			velocityContext.put("weixinDto", weixinDto);
			String url = request.getRequestURL() + "?"
					+ request.getQueryString();
			if (url.indexOf("#") != -1) {
				url = url.substring(0, url.indexOf("#"));
			}
		} catch (DivinationException e) {
			e.printStackTrace();
			LOG.error("divination detail error:{}", e.getMessage());
			velocityContext.put("errCode", e.getDefineCode());
			velocityContext.put("errMsg", e.getMessage());
			viewName=chooseErrorPage(e.getDefineCode());
		} catch (Exception e) {
			e.printStackTrace();
			LOG.error("divination detail error:{}", e);
			velocityContext.put("errCode",DivinationExceptionEnum.SYS_ERROR.getErrCode());
			velocityContext.put("errMsg",DivinationExceptionEnum.SYS_ERROR.getErrChineseMsg());
			viewName= "system/vm/error.vm";
		}

		ViewVelocity.view(request, response, viewName, velocityContext);
	}

	/**
	 * 将摇签的数据添加到数据库
	 * @param wxActDivinationRecord
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/fenshu", method = { RequestMethod.GET,RequestMethod.POST })
	@ResponseBody
	public AjaxJson fenshu(
			@ModelAttribute WxActDivinationRecord wxActDivinationRecord,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		AjaxJson j = new AjaxJson();
		LOG.info("updateRecord parameter wxActDivinationRecord={}.",
				new Object[] { wxActDivinationRecordService });
		try {
			String nickname = "";
			JSONObject userobj = WeiXinHttpUtil.getGzUserInfo(
					wxActDivinationRecord.getOpenid(),
					wxActDivinationRecord.getJwid());

			if (userobj != null && userobj.containsKey("nickname")) {
				nickname = userobj.getString("nickname");
			}
			if (StringUtil.isEmpty(nickname)) {
				nickname = "匿名";
			}
			wxActDivinationRecord.setNickname(EmojiFilter
					.filterEmoji(nickname));
			wxActDivinationRecordService.doAdd(wxActDivinationRecord);
			//更新摇签注册表信息
			WxActDivinationRegistration wxActDivinationRegistration=wxActDivinationRegistrationService.queryRegistrationByOpenidAndActId(wxActDivinationRecord.getOpenid(), wxActDivinationRecord.getActId());
			Date refDate=new Date();
			if(StringUtil.isEmpty(wxActDivinationRegistration.getUseCounts())){
				wxActDivinationRegistration.setUseCounts(1);
			}else{
				wxActDivinationRegistration.setUseCounts(wxActDivinationRegistration.getUseCounts()+1);
			}
			if(StringUtil.isEmpty(wxActDivinationRegistration.getCounts())){
				wxActDivinationRegistration.setCounts(1);
			}else{
				wxActDivinationRegistration.setCounts(wxActDivinationRegistration.getCounts()+1);
			}
			wxActDivinationRegistration.setLastTime(refDate);
		    wxActDivinationRegistrationService.doEdit(wxActDivinationRegistration);
		j.setSuccess(true);
		} catch (DivinationException e) {
			e.printStackTrace();
			j.setSuccess(false);
			j.setMsg(e.getMessage());
			LOG.error("divination fenshu error:{}", e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			j.setSuccess(false);
			j.setMsg("摇签失败失败!");
			LOG.error("divination fenshu error:{}", e.getMessage());
		}

		return j;
	}
	
	/**
	 * 查询数据返回集合给排行榜给页面
	 * @param weixinDto
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/score", method = { RequestMethod.GET,RequestMethod.POST })
	public void score(
			@ModelAttribute WeixinDto weixinDto,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		// 装载微信所需参数
		String jwid = weixinDto.getJwid();
		String appid = weixinDto.getAppid();
		String actId = weixinDto.getActId();
		String viewName = "divination/default/vm/paihangbang.vm";
		VelocityContext velocityContext = new VelocityContext();
		try {
			// 参数验证
			validateBargainDtoParam(weixinDto);
			// 获取活动信息
			WxActDivination divination = divinationService.queryById(actId);
			if (divination == null) {
				throw new DivinationException(
						DivinationExceptionEnum.DATA_NOT_EXIST_ERROR, "活动不存在");
			}

			if (!jwid.equals(divination.getJwid())) {
				throw new DivinationException(
						DivinationExceptionEnum.DATA_NOT_EXIST_ERROR,
						"活动不属于该微信公众号");
			}
			List<WxActDivinationRecord> queryscoreList = wxActDivinationRecordService
					.queryscoreList(actId);
			velocityContext.put("queryscoreList", queryscoreList);			
			velocityContext.put("nonceStr", WeiXinHttpUtil.nonceStr);// 必填，生成签名的随机串
			velocityContext.put("timestamp", WeiXinHttpUtil.timestamp);// 必填，生成签名的时间戳
			velocityContext.put("appId", appid);// 必填，公众号的唯一标识
			velocityContext.put("signature",
			WeiXinHttpUtil.getRedisSignature(request, jwid));// 必填，签名，见附录1
			velocityContext.put("queryscoreList", queryscoreList);
		}  catch (DivinationException e) {
			e.printStackTrace();
			LOG.error("divination score error:{}", e.getMessage());
			velocityContext.put("errCode", e.getDefineCode());
			velocityContext.put("errMsg", e.getMessage());
			viewName=chooseErrorPage(e.getDefineCode());
		} catch (Exception e) {
			e.printStackTrace();
			LOG.error("divination score error:{}", e);
			velocityContext.put("errCode",DivinationExceptionEnum.SYS_ERROR.getErrCode());
			velocityContext.put("errMsg",DivinationExceptionEnum.SYS_ERROR.getErrChineseMsg());
			viewName= "system/vm/error.vm";
		}
		ViewVelocity.view(request, response, viewName, velocityContext);
	}
	
	
	/**
	 * 参数校验方法
	 * @param weixinDto
	 */
	private void validateBargainDtoParam(WeixinDto weixinDto) {
		if (StringUtils.isEmpty(weixinDto.getActId())) {
			throw new DivinationException(
					DivinationExceptionEnum.ARGUMENT_ERROR, "活动ID不能为空");
		}
		if (StringUtils.isEmpty(weixinDto.getOpenid())) {
			throw new DivinationException(
					DivinationExceptionEnum.ARGUMENT_ERROR, "参与人openid不能为空");
		}
		if (StringUtils.isEmpty(weixinDto.getJwid())) {
			throw new DivinationException(
					DivinationExceptionEnum.ARGUMENT_ERROR, "微信原始id不能为空");
		}
	}
	
	/**
	 * 判断要的次数
	 * @param weixinDto
	 * @param request
	 * @param response
	 */
	@ResponseBody
	@RequestMapping(value = "/validateYaoNum", method = { RequestMethod.GET,RequestMethod.POST })
	public void validateYaoNum(@ModelAttribute WeixinDto weixinDto,HttpServletRequest request, HttpServletResponse response){
		try {
			validateBargainDtoParam(weixinDto);
			
		} catch (Exception e) {
			e.printStackTrace();
			// TODO: handle exception
		}
	}
	//update-begin--Author:zhangweijian  Date: 20180320 for：分享获得额外摇签次数
	/**
	 * 分享获得额外摇签次数
	 * @param weixinDto
	 * @param request
	 * @param response
	 * */
	@ResponseBody
	@RequestMapping(value="shareNum",method = { RequestMethod.GET,RequestMethod.POST })
	public AjaxJson shareNum(@ModelAttribute WeixinDto weixinDto,HttpServletRequest request, HttpServletResponse response){
		AjaxJson j=new AjaxJson();
		LOG.info("shareNum parameter WeixinDto={}.",
				new Object[] { weixinDto });
		long start = System.currentTimeMillis();
		try {
			String actId=weixinDto.getActId();
			String openid = weixinDto.getOpenid();
			String type=request.getParameter("type");
			SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
			WxActDivinationShare wxActDivinationShares=wxActDivinationShareService.queryOneByDate(actId, openid, sd.format(new Date()));
			//获取活动信息
			WxActDivination wxActDivination=divinationService.queryById(actId);
			if(wxActDivinationShares==null){
				//插入一条分享记录
				WxActDivinationShare wxActDivinationShare=new WxActDivinationShare();
				wxActDivinationShare.setActId(actId);
				wxActDivinationShare.setOpenid(openid);
				wxActDivinationShare.setShareType(type);
				wxActDivinationShare.setShareTime(sd.format(new Date()));
				wxActDivinationShareService.doAdd(wxActDivinationShare);
				//是否开启分享得次数
				if(wxActDivination.getExtraLuckyDraw()=="1")
				{
					j.setSuccess(true);
					j.setObj("1");
					j.setMsg("恭喜您分享成功！额外获得1次摇签机会！");
				}
				else{
					j.setObj("0");
					j.setMsg("分享成功！");
				}
				
			}else{
				if(wxActDivination.getExtraLuckyDraw()=="1")
				{
					j.setSuccess(true);
					j.setObj("1");
					j.setMsg("分享成功！");
				}
				else{
					j.setObj("0");
					j.setMsg("分享成功！");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			LOG.error("shareNum error:{}", e);
			j.setSuccess(false);
		}
		LOG.info("shareNum time={}ms.",
				new Object[] { System.currentTimeMillis() - start });
		return j;
	}
	//update-end--Author:zhangweijian  Date: 20180320 for：分享获得额外摇签次数
}